package com.huangguolin.cloud.spring.util;

import com.huangguolin.cloud.spring.entity.MailEntity;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import java.util.Random;

public final class MailUtil {


    /**
     * 随机产生的字符串
     */
    private final static String RAND_STRING =
            "123456789";
    /**
     * 产生随机数
     */
    private final static Random RANDOM = new Random();
    /**
     * 获取随机的验证码
     * @param number 验证码的位数
     * @return
     */
    public static String getVfcCode(Integer number)
    {
        String randomString="";
        int randomIndex;
        char charAt;
        //根据字符串的长度产生随机下标
        for(int i = 0; i < number; i++){
            randomIndex =
                    RANDOM.nextInt(RAND_STRING.length());
            charAt = RAND_STRING.charAt(randomIndex);
            randomString += String.valueOf(charAt);
        }
        return randomString;
    }
    public static void sendMail(MailEntity entity)
            throws EmailException {
        HtmlEmail memail = new HtmlEmail();
        memail.setHostName(entity.getMailHostName());
        memail.setCharset("utf-8");
        memail.addTo(entity.getMaiToUser());
        memail.setFrom(entity.getMailFromUser(), "OBS Cloud");

        memail.setAuthentication(entity.getMailFromUser(),
                entity.getMailFromPwd());
        memail.setSubject(entity.getMailSubject());
        memail.setMsg(entity.getMailContent());
        memail.send();
    }
    public static String getEmailcode(String emailCode) {
        MailEntity mailEntity = new MailEntity();
        mailEntity.setMailHostName("smtp.163.com");

        mailEntity.setMailFromUser("18407815502@163.com");
        mailEntity.setMailFromPwd("20010707hgl");
        mailEntity.setMailSubject("云盘项目验证信息");
        String code = getVfcCode(4);
        mailEntity.setMailContent("验证码："+code+"此验证码仅用于用户注册使用，请妥善保管，勿泄露！");

        mailEntity.setMaiToUser(emailCode);
        try {
            sendMail(mailEntity);
        } catch (EmailException e) {
            e.printStackTrace();
        }

        return code;
    }
}


